<?php

// phpMyRealty 3
//
// File Name: sendmessage.php
// File Location : ./
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');

include ( './config.php' );
include ( PATH . '/defaults.php' );

generateCaptcha();
 
$rand = mt_rand(1, 999);

// ----------------------------------------------------------------------
// SEND MESSAGE SECTION

// Title tag content
$title = $conf['website_name_short'] . ' - ' . $lang['Mailer'];

//Template header
include ( PATH . '/templates/' . $cookie_template . '/header.php' );

// We make sure that the id variable is correct
if ((isset($_GET['id']) && eregi('^[0-9]+$', $_GET['id'])) || (isset($_GET['id']) && isset($_GET['listing']) && eregi('^[0-9]+$', $_GET['id']) && eregi('^[0-9]+$', $_GET['listing']))) {

  // Navigation
  echo table_header ( $lang['Navigation'] );

  // Check if this user exist
  $sql = 'SELECT * FROM ' . USERS_TABLE . ' WHERE id = "' . $_GET['id'] . '" LIMIT 1';
  $r = $db->query($sql);
  $f = $db->fetcharray($r);

  echo '- <a href="' . URL . '/">' . $lang['Menu_Home'] . '</a><br />';

  if ($conf['rewrite'] == 'ON')
   echo '- <a href="' . URL . '/Realtor/' . $_GET['id'] . '.html">' . $lang['Search_Back_To'] . ' ' . $f['first_name'] . ' ' . $f['last_name'] . '</a><br />';
  else
   echo '- <a href="' . URL . '/viewuser.php?id=' . $_GET['id'] . '">' . $lang['Search_Back_To'] . ' ' . $f['first_name'] . ' ' . $f['last_name'] . '</a><br />';

  if (isset($_GET['listing']) && is_numeric($_GET['listing'])) {
   // Check if this listing exists
   $sql = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE id = "' . $_GET['listing'] . '" LIMIT 1';
   $r1 = $db->query($sql);
   $f1 = $db->fetcharray($r1);
   if ($conf['rewrite'] == 'ON')
    echo '- <a href="' . URL . '/Listing/' . rewrite(getnamebyid(TYPES_TABLE, $f1['type'])) . '/' . intval($_GET['listing']) . '_' . rewrite($f['title']) . '.html">' . $lang['Search_Back_To'] . ' ' . $f1['title'] . '</a><br />';
   else
    echo '- <a href="' . URL . '/viewlisting.php?id=' . intval($_GET['listing']) . '">' . $lang['Search_Back_To'] . ' ' . $f1['title'] . '</a><br />';
  }

  $usersearch = $session->fetch('usersearchvariables');
  $listingsearch = $session->fetch('listingsearchvariables');

  // If user search cache is not empty we print the link
  // to the latest user search results
  if (!empty($usersearch))
   echo '- <a href="' . URL . '/usersearch.php?' . $session->fetch('usersearchvariables') . '">' . $lang['Search_Back_User'] . '</a><br />';

  // If listings search cache is not empty we print the link
  // to the latest listings search results
  if (!empty($listingsearch))
   echo '- <a href="' . URL . '/search.php?' . $session->fetch('listingsearchvariables') . '">' . $lang['Search_Back_Listing'] . '</a><br />';

  echo table_footer ();

  //

  // If the Submit button was pressed we start this routine
  if (isset($_POST['submit_mailer']) 
  && $_POST['submit_mailer'] == $lang['Mailer_Submit'])
   {

    $form = array();

    // safehtml() all the POST variables
    // to insert into the database or
    // print the form again if errors
    // found
    $form = array_map('safehtml', $_POST);

    echo table_header ( $lang['Information'] );

    // Initially we think that no errors were found
    $count_error = 0;

    if ( strtoupper($_POST['security']) != $_SESSION['random'] )
     { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Security_Code'] . ' </span><br />'; $count_error++;}

    // Check if email is banned
    $sql = 'SELECT * FROM ' . BANS_TABLE . ' WHERE name = "' . $form['e_mail'] . '" LIMIT 1';
    $r = $db->query($sql) or error ('Critical Error', mysql_error () );

    if ($db->numrows($r) > 0 )
     { echo $lang['e_mail_Banned'] . '<br />'; $count_error++;}
 
    // Check for the empty or incorrect required fields
    if (empty($form['e_mail']) || strlen($form['e_mail']) < 4  || !valid_email($form['e_mail']))
     { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Mailer_e_mail'] . '</span><br />'; $count_error++;}

    if ( (time() - $session->fetch('mail_time')) < 30 )
     { echo $lang['Flood_Detected'] . '<br />'; $count_error++;}

    if (empty($form['message']) || strlen($form['message']) < 4 )
     { echo $lang['Field_Empty'] . ' - <span class="warning">' . $lang['Mailer_Message'] . '</span><br />'; $count_error++;}

    // Check if this user exist
    $sql = 'SELECT * FROM ' . USERS_TABLE . ' WHERE id = "' . $_GET['id'] . '" LIMIT 1';
    $r = $db->query($sql);
    $res = $db->numrows($r);

    if ($res < 1)
     { echo $lang['Mailer_User_Not_Found'] . '<br />'; $count_error++;}

    if ($count_error > '0')
     echo '<br /><span class="warning">' . $lang['Errors_Found'] . ': ' . $count_error . '</span><br />';

    // If no errors were found during the above checks we continue
    if ($count_error == '0')
     {

      if ( strtoupper($_POST['security']) == $_SESSION['random'] ) $session->varunset('random');

      $f = $db->fetcharray($r);

//

      $mail = new PHPMailer();

      if(PHPMAILER == '3') {
       $mail->IsSMTP(); // set mailer to use SMTP
       $mail->Host = $smtp['host'];  // specify main and backup server
       $mail->SMTPAuth = true;     // turn on SMTP authentication
       $mail->Username = $smtp['login'];  // SMTP username
       $mail->Password = $smtp['password']; // SMTP password
      }
      elseif(PHPMAILER == '2') {
       $mail->IsSendmail(); // set mailer to use SMTP
      }
      else {
      }

      $mail->From = $form['e_mail'];
      $mail->FromName = $form['e_mail'];
      $mail->AddAddress($f['email']);

      $lang['Mailer_Subject'] = str_replace('{website_name}', $conf['website_name'], $lang['Mailer_Subject']);
      $lang['Mailer_Subject'] = str_replace('{user_e_mail}', $form['e_mail'] , $lang['Mailer_Subject']);

      $mail->Subject = $lang['Mailer_Subject'];

      if (isset($_GET['listing'])) {
       $sql3 = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE id = "' . $_GET['listing'] . '" LIMIT 1';
       $r3 = $db->query($sql3);
       $f3 = $db->fetcharray($r3);
       $mail->MsgHTML = $form['message'] . ' Listing: ' . $f3['title'] . ' (' . $f3['id'] . ')';
       $mail->AltBody = removehtml($form['message'] . ' Listing: ' . $f3['title'] . ' (' . $f3['id'] . ')');
      }
      else {
       $mail->MsgHTML = $form['message'];
       $mail->AltBody = removehtml($form['message']);
      }

      $mail->Send();

      // Show the Thank you message
      $lang['Mailer_Sent'] = str_replace('{name}', $f['first_name'] . ' ' . $f['last_name'], $lang['Mailer_Sent']);

      echo $lang['Mailer_Sent'];

      // Save last message post timestamp not to allow
      // this user post again in 30 seconds
      $session->set('mail_time', time());

     }

    echo table_footer ( );

   }

  // If we open sendmessage.php for the first time
  // or there were errors found in the form fields 
  // we output the form again with the old variables 
  // included
  if (!isset($count_error) || $count_error > '0')
   {

    echo table_header ( $lang['Mailer'] );
    
  	// If they have an account
  	if (auth_check($session->fetch('login'), $session->fetch('password')))
  	{
		  // Fetching the user ID from the user's table
		  $sql = 'SELECT approved, id, package FROM ' . USERS_TABLE . ' WHERE login = "' . $session->fetch('login') . '" LIMIT 1';
		  $r = $db->query( $sql );
		  $f = $db->fetcharray( $r );
		  
		  $account = true;
		  
		  if ($f['package'] > 0)
		  	$paid_account = true;
		  else
		  	$paid_account = false;
  	}
  	else
  	{
  		$paid_account = false;
  		$account = false;
  	}
  
	// Account only, but they don't have an account
	if ($conf['contact_agents'] == '2' && $account == false)
	{
		$disable = true;
		$agent_details = $lang['Agent_Details_Account_Only'];
	}
	// Paid account only, but they don't have a paid account
	elseif ($conf['contact_agents'] == '3' && $paid_account == false)
	{
		$disable = true;
		$agent_details = $lang['Agent_Details_Pay_Only'];
	}
	
	if ($disable == true)
	{
		echo $agent_details;
	}
		else
	{

	    // Define the form variables if the form is loaded for the first time
	    if (!isset($form))
	     {
	      $form = array();
	      $form['e_mail'] = '';
	      $form['message'] = '';
	     }
	
	    // Output the form
	
	 if (isset($_GET['listing'])) 
	    echo '
	     <form action="' . URL . '/sendmessage.php?id=' . $_GET['id'] . '&listing=' . $_GET['listing'] . '" method="POST">
	      <table width="100%" cellpadding="5" cellspacing="0" border="0">
	         ';
	 else
	    echo '
	     <form action="' . URL . '/sendmessage.php?id=' . $_GET['id'] . '" method="POST">
	      <table width="100%" cellpadding="5" cellspacing="0" border="0">
	         ';
	
	    // Check if this user exist
	    $sql = 'SELECT * FROM ' . USERS_TABLE . ' WHERE id = "' . $_GET['id'] . '" LIMIT 1';
	    $r = $db->query($sql);
	    $f = $db->fetcharray($r);
	
	 if (isset($_GET['listing'])) {
	    $sql2 = 'SELECT * FROM ' . PROPERTIES_TABLE . ' WHERE id = "' . $_GET['listing'] . '" LIMIT 1';
	    $r2 = $db->query($sql2);
	    $f2 = $db->fetcharray($r2);
	    echo userform ($lang['Mailer_To'] , $f['first_name'] . ' ' . $f['last_name'] . ' (' . $f2['title'] . ')');
	 }
	 else
	    echo userform ($lang['Mailer_To'] , $f['first_name'] . ' ' . $f['last_name']);
	
	    echo userform ($lang['Mailer_e_mail'], '<input type="text" size="45" name="e_mail" value="' . $form['e_mail'] . '" maxlength="255">', '1');
	    echo userform ($lang['Mailer_Message'], '<textarea cols="45" rows="4"  name="message" onKeyDown="textCounter(this.form.message,this.form.message_counter, ' . $conf['mailer_message_size'] . ');" onKeyUp="textCounter(this.form.message,this.form.message_counter, ' . $conf['mailer_message_size'] . ');">' . unsafehtml($form['message']) . '</textarea>', '1');
	    echo userform ('', '<input readonly type="text" name="message_counter" size="5" maxlength="5" value="' . $conf['mailer_message_size'] . '"> ' . $lang['Characters_Left']);
	
	    echo userform ($lang['Security_Code'], '<img src="' . URL . '/security.php?' . $rand . '" border="0" alt=""><input type="text" size="25" name="security" value="" maxlength="255">' , '1');
	 
	    echo userform ('', '<input type="Submit" class="submit" name="submit_mailer" value="' . $lang['Mailer_Submit'] . '">');
	
	    echo '
	      </table>
	     </form>
	    ';
	  }
	
	    echo table_footer ();
   }

 }

else

 echo 'Sorry, ID is not specified or incorrect';

// Template footer
include ( PATH . '/templates/' . $cookie_template . '/footer.php' );

?>